home *** CD-ROM | disk | FTP | other *** search
- Path: li.net!jeremy
- From: jeremy@newshost.li.net (Jeremy Markman)
- Newsgroups: comp.lang.c
- Subject: Re: Recursion Question
- Date: 5 Apr 1996 14:26:19 GMT
- Organization: LI Net (Long Island Network)
- Message-ID: <4k3aib$sf@linet06.li.net>
- References: <4k14o1$2k2@isis.fiu.edu>
- NNTP-Posting-Host: linet04.li.net
- X-Newsreader: TIN [version 1.2 PL2]
-
- Mark Romano (mark@serss1.fiu.edu) wrote:
- : I am trying to find some recursive functions that will convert a number into
- : a binary. I need one that will print out the numbers as they are
- : generated and I also need one that will hold the binary digits in memory
- : and then printed out with a single printf statement. Can any one help??
-
- char *tobinary(int decimal)
- {
- int remainder;
- char *binary;
- char *binary2;
-
- if (decimal == 0)
- return("");
- binary = tobinary(decimal / 2);
- binary2 = malloc(strlen(binary) + 2);
- strcpy(binary2,binary);
- binary2[strlen(binary2) + 1] = '\0';
- binary2[strlen(binary2)] = '0' + (decimal % 2);
- return(binary2);
- }
-
- This is rough, as their will be some memory loss (I don't deallocate
- memory, for instance) and I'm sure the code can be pared down, but this
- is off the top of my head...
-
- This uses the basic binary conversion algorithm where you keep dividing
- the decimal number by 2, concatinating the remainder as the most
- significant digit to the binary number. Of course, since recursion turns
- this around, you have to remember to concat. the remainder as the least
- significant digit of the binary string returned...
-